package com.example.demo.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.PageBean;
import com.example.demo.pojo.MarkDownInfo;
import com.example.demo.pojo.MarkDownInfoMap;
import com.example.demo.pojo.SysUser;
import com.example.demo.pojo.SysUserMap;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Controller
public class TestController {
	@Autowired
	private SysUserMap sysUserMap;
	@Autowired
	private MarkDownInfoMap markDownInfo;
	@RequestMapping("/getAll")
	@ResponseBody
	public String getAll(HttpServletRequest request){
		int currentPage= Integer.valueOf(request.getParameter("page"));
		int pageSize = Integer.valueOf(request.getParameter("limit"));;
		//设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
		PageHelper.startPage(currentPage, pageSize);
		Page<MarkDownInfo> list = (Page<MarkDownInfo>) markDownInfo.getAllMarkDownInfo();
		int snum = (int) list.getTotal();
        PageBean<MarkDownInfo> pageData = new PageBean<MarkDownInfo>(currentPage, pageSize,snum);
        pageData.setItems(list);
        List liss = pageData.getItems();
        JSONObject json = new JSONObject();
        json.put("data", liss);
        json.put("count", snum);
        return json.toJSONString();		
	}
	@RequestMapping("/freemarker")
    public String freemarker(Map<String, Object> map){
        map.put("name", "Joe");
        map.put("sex", 1);    //sex:性别，1：男；0：女；  
        
        // 模拟数据
        List<Map<String, Object>> friends = new ArrayList<Map<String, Object>>();
        Map<String, Object> friend = new HashMap<String, Object>();
        friend.put("name", "xbq");
        friend.put("age", 22);
        friends.add(friend);
        friend = new HashMap<String, Object>();
        friend.put("name", "July");
        friend.put("age", 18);
        friends.add(friend);
        map.put("friends", friends);
        return "hello";
    }
	    /**
	     * 没有加shiro权限注解
	     * @return
	     */
	    @GetMapping("/test1/{id}")
	    public String test1(@PathVariable("id")String id, Map<String, Object> map){
	    	MarkDownInfo mark = markDownInfo.getMarkDownInfo(id);
	    	map.put("content", mark.getHtmlcontent());
	        return "showMark";
	    }

	    /**
	     * 添加了shiro权限注解，需要用户有"systemUserAdd"权限
	     * @return
	     */
	    @RequestMapping(value="/test2",method= RequestMethod.POST)
	    @RequiresPermissions("systemUserAdd")
	    @ResponseBody
	    public String test2(HttpServletRequest request){
	    	SysUser user  = (SysUser) SecurityUtils.getSubject().getPrincipal();
	    	String htmlText = request.getParameter("text");
	    	String title = request.getParameter("title");
	    	MarkDownInfo mark = new MarkDownInfo();
	    	mark.setId(UUID.randomUUID().toString());
	    	mark.setUserid(user.getUserId());
	    	mark.setGroupid("1");
	    	mark.setHtmlcontent(htmlText);
	    	mark.setUpdatetime(new Date());
	    	mark.setTitle(title);
	    	markDownInfo.insertMarkdown(mark);
	        return "success";
	    }
	    /**
	     * 图片上传
	     * @param filess
	     * @param request
	     * @param response
	     */
	    @RequestMapping(value="/imgUpload",method= RequestMethod.POST)
	    @RequiresPermissions("systemUserAdd")
	    public void imgUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile filess, HttpServletRequest request,HttpServletResponse response){
	    	//项目的所在地，加上定义的uploadImg文件
	    	String saveBeginpath = "D://ttss/uploadImg";
	    	File uploadPath = new File(saveBeginpath);
	    	//获取input中name值，目前是获取多张图片
	    	List<MultipartFile> files = new ArrayList<MultipartFile>(); // 获取图片
	    	files.add(filess);
	    	// 判断上传文件的保存目录是否存在
	    	if (!uploadPath.exists() && !uploadPath.isDirectory()) {
	    	// 创建目录
	    		uploadPath.mkdir();
	    	}
	    	String path = request.getContextPath();
	        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
	    	//遍历图片
	    	for (MultipartFile picture : files) {
	    	//获取类型，只能获取传入的简单类型,文件的后缀
	    	String type = picture.getContentType();
	    	//如果type中不包含image，代表不是图片格式
	    	if(type.indexOf("image")!=-1){
	    	//是图片
	    	//判断是否是图片格式
	    	try {
	    	//只有图片才能转义
	    	BufferedImage image1 = ImageIO.read(picture.getInputStream());
	    	if (image1 != null) {// 如果image=null 表示上传的不是图片格式
	    	System.out.println(image1.getWidth());// 获取图片宽度，单位px
	    	System.out.println(image1.getHeight());// 获取图片高度，单位px
	    	}else{
	    	break;
	    	}
	    	} catch (IOException e) {
	    	e.printStackTrace();
	    	}
	    	}else{
	    	break;
	    	}
	    	String  savepath =null;
	    	String uuid = UUID.randomUUID().toString();
	    	String paths = picture.getName() +uuid+".jpg";
	    	savepath = saveBeginpath + File.separator + paths;
	    	paths = "http://localhost:8089/uploadImg/"+paths;
	    	try {
	    	//Spring的将文件上传到服务器上
	    	picture.transferTo(new File(savepath));
			response.getWriter().write("{\"success\":1,\"messgae\":\"upload successful\",\"url\":\""+paths+"\"}");
	    	} catch (Exception e) {
	    	e.printStackTrace();
	    	}
	    }
   }
}
